#ifndef Server_h
#define Server_h 1

// Agents
#include "agents.h"

BEGIN_GOODS_NAMESPACE

class RMT_CLASS_EXPORT CAbstractServer 
{
public:
	CAbstractServer(int max_clients = 10)
		: opened(False),
		n_clients(0),
		local_gateway(NULL),
		global_gateway(NULL),
		term_event(cs),
		n_max_clients(max_clients)
	{
//		log = fopen("run.log", "w+");
//		console::use_log_file(log);
	}
	virtual ~CAbstractServer();
	
	virtual int Open (int nport);
	unsigned int GetClientsNumber ();
	const char* GetServerName () const;
	void RemoveClientAgent (CClientAgent *agent);
	void Close ();

	void SetMaxClientsNumber (unsigned int num);
	unsigned int GetMaxClientsNumber ();
		
protected:
	enum { MAX_LOGIN_NAME = 64 };
	virtual CClientAgent * OnCreateClientAgent () = 0;
	//	accept connections
	virtual void accept (socket_t* gateway);
	mutable mutex cs;
	
private:
	char  name[MAX_LOGIN_NAME];

	//	is server openned
	bool opened;
	FILE* log;
	l2elem clients;
	unsigned int n_clients;
	unsigned int n_max_clients;
	
	// gatewayڸԵacceptڣ̼߳ͬ
	socket_t* local_gateway;
	socket_t* global_gateway;
	int n_opened_gateways;

	eventex term_event;

	static void task_proc start_local_gatekeeper (void* arg);
	static void task_proc start_global_gatekeeper (void* arg);
	friend class GOODS_DLL_EXPORT CClientAgent;
};

END_GOODS_NAMESPACE


#endif
